package czx.wt.util.request;

import com.alibaba.fastjson.JSON;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: RequestContextUtil工具类
 * @Author: ChenZhiXiang
 * @CreateDate: 2018/12/25 0025 17:16
 * @Version: 1.0
 */
public class RequestContextUtil {

    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取Request
     * @return
     */
    public static HttpServletRequest getRequest() {
        //TODO:单元测试的时候，还是会得到requestAttributes，不等于null
        ServletRequestAttributes requestAttributes = getRequestAttributes();
        if (requestAttributes != null) {
            return requestAttributes.getRequest();
        } else {
            return null;
        }
    }

    /**
     * 获取Response
     * @return
     */
    public static HttpServletResponse getResponse() {
        //TODO:单元测试的时候，还是会得到requestAttributes，不等于null
        ServletRequestAttributes requestAttributes = getRequestAttributes();
        if (requestAttributes != null) {
            return requestAttributes.getResponse();
        } else {
            return null;
        }
    }

    /**
     * 获取SessionId
     * @return
     */
    public static String getSessionId() {
        //TODO:单元测试的时候，还是会得到requestAttributes，不等于null
        ServletRequestAttributes requestAttributes = getRequestAttributes();
        if (requestAttributes != null) {
            return requestAttributes.getSessionId();
        } else {
            return null;
        }
    }

    /**
     * 往前端写数据
     * @param object
     */
    public static void writeToResponse(Object object) {
        PrintWriter writer = null;
        try {
            HttpServletResponse response = RequestContextUtil.getResponse();
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-type", "text/html;charset=utf-8");
            writer = response.getWriter();
            writer.write(JSON.toJSONString(object));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.close();
        }
    }
}
